package cn.com.surker.interceptor;

import cn.com.surker.redis.RedisUtils;
import cn.com.surker.system.model.CacheUser;
import cn.com.surker.util.StringUtils;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 自定义插入字段
 *
 * @author luotao
 * @date 2024/10/9
 */
// @Component
public class UpdateMetaObjectHandler implements MetaObjectHandler {

	@Resource
	protected RedisUtils redisUtils;

	@Override
	public void insertFill(MetaObject metaObject) {
		//
		System.err.println("插入数据啦");
		// 假设当前登录人员信息可以通过getCurrentLoginName()获取
		Object creator = metaObject.getValue("creator");
		if (creator == null) {
			String currentLoginName = getCurrentLoginName();
			if (StringUtils.isNotBlank(currentLoginName)) {
				// 设置字段值，
				this.strictInsertFill(metaObject, "creator", String.class, currentLoginName);
			}
		}
	}

	@Override
	public void updateFill(MetaObject metaObject) {
		System.err.println("更新数据了");
		Object updator = metaObject.getValue("updator");
		if (updator == null) {
			String currentLoginName = getCurrentLoginName();
			if (StringUtils.isNotBlank(currentLoginName)) {
				// 设置字段值，
				this.strictInsertFill(metaObject, "updator", String.class, currentLoginName);
			}
		}

	}

	private String getCurrentLoginName() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String access_token = (String) request.getSession().getAttribute("oauth_token");
		if (redisUtils.exists(access_token)) {
			CacheUser user = (CacheUser) redisUtils.get(access_token);
			if (user != null) {
				return user.getName();
			}
		}
		return null;
	}


}
